<template>
  <div>
    <h1>登录页面</h1>
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
    >
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="ruleForm.mobile" />
      </el-form-item>
      <el-form-item label="密码" prop="pass">
        <el-input v-model="ruleForm.pass" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          登录
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        <el-button type="primary" @click="onreg"> 注册 </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { userLogin } from "../api/api";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
const router = useRouter();
const ruleFormRef = ref<FormInstance>();
const ruleForm = ref({
  mobile: "",
  pass: "",
});
const onreg = () => {
  router.push("/reg");
};
const rules = ref<FormRules>({
  mobile: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern:
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
      message: "手机格式错误",
      trigger: "blur",
    },
  ],
  pass: [{ required: true, message: "请输入密码", trigger: "blur" }],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      userLogin(ruleForm.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("登陆成功");
          let user = res.data.data;
          let token = user.token;
          sessionStorage.setItem("user", JSON.stringify(user));
          sessionStorage.setItem("token", token);
          router.push("/home");
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}));
</script>
